<?php

namespace App\Admin\Controllers;

use App\Admin\Repositories\ReservationComment;
use App\Models\Reservation;
use App\Models\User;
use Dcat\Admin\Admin;
use Dcat\Admin\Form;
use Dcat\Admin\Grid;
use Dcat\Admin\Layout\Content;
use Dcat\Admin\Show;
use Dcat\Admin\Controllers\AdminController;
use \App\Models\ReservationComment as ReservationCommentModel;
use Dcat\Admin\Support\Helper;
use Dcat\Admin\Widgets\Alert;

class ReservationCommentController extends AdminController
{
    public function index(Content $content)
    {
        $reservation = Reservation::find(request()->rid);
        return $content
            ->header('评论')
            ->description($reservation ? trunc_title($reservation->content, 30) : '')
            ->breadcrumb('评论')
            ->body($this->grid());
    }

    /**
     * Make a grid builder.
     *
     * @return Grid
     */
    protected function grid()
    {
        return Grid::make(ReservationCommentModel::with(['commenter', 'replyer']), function (Grid $grid) {

            // 已绑定用户的专家可回复、评论
            $show_replay_btn = Admin::user()['user_id'] ? Admin::user()['user_id'] : 0;

            $grid->model()->where('reservation_id', request()->rid);
            $grid->model()->orderBy('is_expert', 'desc')->orderBy('zan_num', 'desc')->orderBy('id', 'desc');

            $grid->column('id')->sortable();
            $grid->column('commenter', '发布者') ->display(function($commenter){
                return ($commenter['real_name'] ? $commenter['real_name'] : $commenter['user_name']) . ($this->is_expert ? '（专家）' : '');
            });
            $grid->column('content')->display(function ($content) {

                if ($this->reply_user_id) {
                    $repler_name = ($this->replyer['real_name'] ? $this->replyer['real_name'] : $this->replyer['user_name']);
                    $content = '回复 ' . '<a style="color:#495abf;">' . $repler_name . '</a>：' . $content;
                }
                return $content;
            })->width('30%');

            $grid->column('file','图片、视频')
                ->if (function () {
                    return $this->imgs;
                })
                ->display(function () {
                    $img_arr = json_decode($this->imgs, true);
                    return $img_arr ? $img_arr[0] : '';
                })
                ->image('', 60, 60)
                ->else()
                ->display(function(){
                    $html = '';
                    if ($this->video) {
                        $html = '<a href="'.config('app.img_url') . $this->video.'" target="_blank"><i class="fa fa-video-camera"></i>  查看</a>';
                    }
                    return $html;
                });

            $grid->column('created_at', '评论时间');
            $grid->column('zan_num', '点赞数');
            $grid->column('is_show', '展示')->switch();

            $grid->quickSearch(['commenter.real_name', 'commenter.user_name', 'replyer.real_name', 'replyer.user_name', 'content'])->placeholder('搜索...');

            if ($show_replay_btn) {
                $grid->actions(function ($actions) {
                    $id = $actions->getKey();
                    $edit_page = admin_base_path('reservation_comment/create?rid='.request()->rid.'&comment_id='.$id);
                    $actions->append("<a href=".$edit_page."><i class='fa fa-reply'></i> 回复</a>");
                });

                $add_url = admin_base_path('reservation_comment/create?rid='.request()->rid);
                $add_btn_html = '<a href="'.$add_url.'" class="btn btn-primary btn-outline pull-right"><i class="feather icon-plus"></i><span class="d-none d-sm-inline">&nbsp;&nbsp;发布评论</span></a >';
                $grid->tools($add_btn_html);
            }

            $list_url = admin_base_path('reservation');
            $list_btn_html = '<a href="'.$list_url.'" class="btn btn-primary btn-outline pull-right" style="margin-right: 10px;"><span class="d-none d-sm-inline">返回列表</span></a >';
            $grid->tools($list_btn_html);

            $grid->disableEditButton();
            $grid->disableViewButton();
            $grid->disableCreateButton();
            $grid->enableDialogCreate();

        });
    }

    /**
     * Make a show builder.
     *
     * @param mixed $id
     *
     * @return Show
     */
    protected function detail($id)
    {
        return Show::make($id, new ReservationComment(), function (Show $show) {
            $show->field('id');
            $show->field('content');
            $show->field('imgs');
            $show->field('video');
            $show->field('reservation_id');
            $show->field('zan_num');
            $show->field('reply_id');
            $show->field('reply_user_id');
            $show->field('user_id');
            $show->field('is_show');
            $show->field('created_at');
            $show->field('updated_at');
        });
    }

    /**
     * Make a form builder.
     *
     * @return Form
     */
    protected function form()
    {
        return Form::make(new ReservationComment(), function (Form $form) {

            $reservation = Reservation::find(request()->rid);
            if ($reservation) {
                $reservation_html = '话题内容：' . $reservation->content;
                $form->html(Alert::make($reservation_html)->info());
            }

            $comment_id = request()->comment_id ?? 0;
            $reply_user_id = 0;
            if ($comment_id) {
                $comment = ReservationCommentModel::with(['commenter', 'replyer'])->find($comment_id);
                if ($comment) {
                    $reply_user_id = $comment->user_id;
                }

                $common_html = '回复 ' . ($comment->commenter->real_name ?? $comment->commenter->user_name) . '：' . $comment->content;
                $form->html(Alert::make($common_html)->info());
            }

            $form->display('id');
            $form->text('content')->required();
            $typeOptions = [1 => '图文', 2 => '视频'];
            $form->radio('types', '类型')
                ->when([1], function (Form $form) {
                    $form->image('imgs')->move('api/reservation_comment_img/'.date('Y-m-d'))->autoUpload()->saving(function ($paths) {
                        $paths = Helper::array($paths);
                        return json_encode($paths, true); // 最终转化为json保存到数据库
                    })->customFormat(function ($paths) {
                        return Helper::array($paths); // 转为数组
                    })->help('评论仅可上传1张图片');


                })
                ->when(2, function (Form $form) {
                    $form->file('video', '短视频')->move('api/reservation_comment_video/'.date('Y-m-d'))->disableChunked()->maxSize(1024 * 50)->accept('mp4')->autoUpload()->help('视频文件要求mp4格式且不超过50M');
                })
                ->options($typeOptions)
                ->default(1);

            $form->radio('is_show', '是否展示')->options([1 => '是', 0 => '否'])->default(1);
            $form->number('zan_num');


            $form->hidden('reservation_id')->value(request()->rid);
            $form->hidden('reply_id')->value($comment_id);
            $form->hidden('reply_user_id')->value($reply_user_id);
            $form->hidden('user_id')->value(Admin::user()->user_id);
            $form->hidden('is_expert')->value(1);
            $form->hidden('video_img');

            $form->display('created_at');
            $form->display('updated_at');

            $form->disableViewCheck();
            $form->disableEditingCheck();
            $form->disableCreatingCheck();

            $form ->saving(function($form){
                // 生成视频截图
                if ($form->types == 2 && $form->video) {
                    $stream_path = public_path('/uploads/'.$form->video);
                    $video_cover_name = 'api/reservation_comment_video/'.get_file_name($stream_path).'.jpg';
                    $form->video_img = get_video_cover($stream_path, $video_cover_name);
                }
                $form->deleteInput(['types']);
            });

            $form->saved(function (Form $form) {
                $reservation = Reservation::find($form->reservation_id);
                if ($reservation->expert_comment_state == 0) {
                    $reservation->expert_comment_state = 1; // 专家已回复
                    $reservation->save();
                }
                return $form->redirect('reservation_comment?rid='.$form->reservation_id, '保存成功');
            });
        });
    }
}
